package com.brtbeacon.oauth2.verifytoken.utils;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Locator;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.FailureMode;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import net.spy.memcached.transcoders.SerializingTranscoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 *
 * 阿里云缓存
 *
 * @author zswlkj
 *
 */
public class OcsSample {

	private static final Logger log = LoggerFactory.getLogger(OcsSample.class);

	public OcsSample(CacheConfig config){
		inti(config);
	}
	private static int exp=0 ;
	private static MemcachedClient cache = null;


	public void inti(CacheConfig config){
		try {
			exp =config.getExp();
			AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"},
					new PlainCallbackHandler(config.getUsername(), config.getPassword()));

			//设置默认的转码器
			SerializingTranscoder transcoder = new SerializingTranscoder();
			transcoder.setCompressionThreshold(1024);

			cache = new MemcachedClient(
					new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
							.setFailureMode(FailureMode.Redistribute)
							.setLocatorType(Locator.CONSISTENT)
							.setOpTimeout(500)
							.setTimeoutExceptionThreshold(1998)
							.setTranscoder(transcoder)
							.setAuthDescriptor(ad).build(),

					AddrUtil.getAddresses(config.getHost() + ":" + config.getPort()));
		} catch (IOException e) {
			log.error(" =============== 初始化阿里云缓存系统：", e);
		}
	}





	public void set(String key, Object value){
		try {
			cache.set(key, exp, value);
		} catch (Exception e) {
			log.error(" =============== 设置阿里云缓存：", e);
		}
	}

	public void set(String key, Object value, int exp){
		try {
			cache.set(key, exp, value);
		} catch (Exception e) {
			log.error(" =============== 设置阿里云缓存：", e);
		}
	}

	public Object get(String key){
		try {
			return cache.get(key);
		} catch (Exception e) {
			log.error(" =============== 获取阿里云缓存：", e);
			return null;
		}
	}

	public void remove(String key){
		try {
			cache.delete(key);
		} catch (Exception e) {
			log.error(" =============== 获取阿里云缓存：", e);
		}
	}
}